<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提示词管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            color: #4285f4;
            margin-bottom: 15px;
        }
        
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .tab-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 20px;
            background: #e0e0e0;
            color: #666;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .tab-btn.active {
            background: #4285f4;
            color: white;
        }
        
        .stats {
            display: flex;
            gap: 30px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #4285f4;
        }
        
        .stat-label {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .controls {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .search-input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: #4285f4;
            color: white;
        }
        
        .btn-primary:hover {
            background: #3367d6;
        }
        
        .btn-success {
            background: #4caf50;
            color: white;
        }
        
        .btn-success:hover {
            background: #45a049;
        }
        
        .btn-warning {
            background: #ff9800;
            color: white;
        }
        
        .btn-warning:hover {
            background: #e68900;
        }
        
        .btn-danger {
            background: #f44336;
            color: white;
        }
        
        .btn-danger:hover {
            background: #d32f2f;
        }
        
        .prompts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .prompt-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .prompt-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        }
        
        .image-container {
            width: 100%;
            height: 200px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        
        .prompt-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .image-placeholder {
            color: #6c757d;
            font-size: 14px;
        }
        
        .prompt-content {
            padding: 15px;
        }
        
        .prompt-text {
            font-size: 14px;
            line-height: 1.4;
            color: #333;
            margin-bottom: 10px;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .prompt-meta {
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
        }
        
        .prompt-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 30px;
        }
        
        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .pagination button:hover:not(:disabled) {
            background: #f5f5f5;
        }
        
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination .current-page {
            background: #4285f4;
            color: white;
            border-color: #4285f4;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            color: #333;
        }
        
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .toast.success {
            background: #4caf50;
        }
        
        .toast.error {
            background: #f44336;
        }
        
        .toast.warning {
            background: #ff9800;
        }
        
        .toast.show {
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>提示词管理系统</h1>
            
            <div class="tabs">
                <button class="tab-btn active" id="allTab">全部</button>
                <button class="tab-btn" id="favoriteTab">收藏</button>
            </div>
            
            <div class="stats">
                <div class="stat-item">
                    <div class="stat-number" id="totalCount">0</div>
                    <div class="stat-label">总数量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="favoriteCount">0</div>
                    <div class="stat-label">收藏数量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="currentPage">1</div>
                    <div class="stat-label">当前页</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="totalPages">1</div>
                    <div class="stat-label">总页数</div>
                </div>
            </div>
            
            <div class="controls">
                <input type="text" id="searchInput" class="search-input" placeholder="搜索提示词...">
                <button class="btn btn-primary" id="searchBtn">搜索</button>
                <button class="btn btn-success" id="syncBtn">同步Chrome数据</button>
                <button class="btn btn-warning" id="exportBtn">导出CSV</button>
            </div>
        </div>
        
        <div id="loading" class="loading" style="display: none;">
            加载中...
        </div>
        
        <div id="promptsContainer" class="prompts-grid"></div>
        
        <div id="emptyState" class="empty-state" style="display: none;">
            <h3>暂无数据</h3>
            <p>点击"同步Chrome数据"按钮从Chrome插件同步数据</p>
        </div>
        
        <div id="pagination" class="pagination" style="display: none;"></div>
    </div>
    
    <script>
        class PromptManager {
            constructor() {
                this.currentPage = 1;
                this.perPage = 12;
                this.currentTab = 'all';
                this.searchQuery = '';
                this.init();
            }
            
            async init() {
                this.bindEvents();
                await this.loadPrompts();
                await this.loadStats();
            }
            
            bindEvents() {
                // 标签页切换
                document.getElementById('allTab').addEventListener('click', () => {
                    this.switchTab('all');
                });
                
                document.getElementById('favoriteTab').addEventListener('click', () => {
                    this.switchTab('favorite');
                });
                
                // 搜索
                document.getElementById('searchBtn').addEventListener('click', () => {
                    this.search();
                });
                
                document.getElementById('searchInput').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.search();
                    }
                });
                
                // 同步数据
                document.getElementById('syncBtn').addEventListener('click', () => {
                    this.syncFromChrome();
                });
                
                // 导出数据
                document.getElementById('exportBtn').addEventListener('click', () => {
                    this.exportData();
                });
            }
            
            async loadPrompts() {
                try {
                    this.showLoading(true);
                    
                    const params = new URLSearchParams({
                        page: this.currentPage,
                        per_page: this.perPage,
                        search: this.searchQuery,
                        favorites_only: this.currentTab === 'favorite'
                    });
                    
                    const response = await fetch(`/api/prompts?${params}`);
                    const result = await response.json();
                    
                    if (result.success) {
                        this.renderPrompts(result.data.prompts);
                        this.updatePagination(result.data.pagination);
                    } else {
                        this.showToast('加载失败: ' + result.error, 'error');
                    }
                } catch (error) {
                    this.showToast('加载失败: ' + error.message, 'error');
                } finally {
                    this.showLoading(false);
                }
            }
            
            async loadStats() {
                try {
                    const response = await fetch('/api/stats');
                    const result = await response.json();
                    
                    if (result.success) {
                        document.getElementById('totalCount').textContent = result.data.total_count;
                        document.getElementById('favoriteCount').textContent = result.data.favorite_count;
                    }
                } catch (error) {
                    console.error('加载统计信息失败:', error);
                }
            }
            
            renderPrompts(prompts) {
                const container = document.getElementById('promptsContainer');
                const emptyState = document.getElementById('emptyState');
                
                if (prompts.length === 0) {
                    container.style.display = 'none';
                    emptyState.style.display = 'block';
                    return;
                }
                
                container.style.display = 'grid';
                emptyState.style.display = 'none';
                
                container.innerHTML = prompts.map(prompt => `
                    <div class="prompt-card">
                        <div class="image-container">
                            ${prompt.image_data ? 
                                `<img src="${prompt.image_data}" alt="Prompt Image" class="prompt-image">` :
                                `<div class="image-placeholder">无图片</div>`
                            }
                        </div>
                        <div class="prompt-content">
                            <div class="prompt-text">${this.escapeHtml(prompt.text)}</div>
                            <div class="prompt-meta">
                                ${prompt.is_favorite ? '❤️ 已收藏' : '🤍 未收藏'} | 
                                ${prompt.source} | 
                                ${new Date(prompt.updated_at).toLocaleDateString()}
                            </div>
                            <div class="prompt-actions">
                                <button class="btn btn-primary btn-small" onclick="promptManager.toggleFavorite(${prompt.id})">
                                    ${prompt.is_favorite ? '取消收藏' : '添加收藏'}
                                </button>
                                <button class="btn btn-danger btn-small" onclick="promptManager.deletePrompt(${prompt.id})">
                                    删除
                                </button>
                            </div>
                        </div>
                    </div>
                `).join('');
            }
            
            updatePagination(pagination) {
                const paginationEl = document.getElementById('pagination');
                document.getElementById('currentPage').textContent = pagination.page;
                document.getElementById('totalPages').textContent = pagination.pages;
                
                if (pagination.pages <= 1) {
                    paginationEl.style.display = 'none';
                    return;
                }
                
                paginationEl.style.display = 'flex';
                
                let paginationHTML = '';
                
                // 上一页
                paginationHTML += `
                    <button ${!pagination.has_prev ? 'disabled' : ''} onclick="promptManager.goToPage(${pagination.page - 1})">
                        上一页
                    </button>
                `;
                
                // 页码
                const startPage = Math.max(1, pagination.page - 2);
                const endPage = Math.min(pagination.pages, pagination.page + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    paginationHTML += `
                        <button class="${i === pagination.page ? 'current-page' : ''}" 
                                onclick="promptManager.goToPage(${i})">
                            ${i}
                        </button>
                    `;
                }
                
                // 下一页
                paginationHTML += `
                    <button ${!pagination.has_next ? 'disabled' : ''} onclick="promptManager.goToPage(${pagination.page + 1})">
                        下一页
                    </button>
                `;
                
                paginationEl.innerHTML = paginationHTML;
            }
            
            switchTab(tab) {
                this.currentTab = tab;
                this.currentPage = 1;
                
                // 更新标签页样式
                document.querySelectorAll('.tab-btn').forEach(btn => {
                    btn.classList.remove('active');
                });
                document.getElementById(tab + 'Tab').classList.add('active');
                
                this.loadPrompts();
            }
            
            search() {
                this.searchQuery = document.getElementById('searchInput').value.trim();
                this.currentPage = 1;
                this.loadPrompts();
            }
            
            async syncFromChrome() {
                try {
                    this.showToast('正在同步Chrome数据...', 'warning');
                    
                    // 这里应该从Chrome插件获取数据
                    // 由于Chrome插件运行在浏览器中，这里使用模拟数据
                    const mockData = {
                        prompts: [
                            {
                                id: Date.now(),
                                text: '这是一个从Chrome插件同步的测试提示词',
                                image: '',
                                source: 'scrape',
                                isFavorite: false
                            }
                        ]
                    };
                    
                    const response = await fetch('/api/sync', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(mockData)
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        this.showToast('同步成功！', 'success');
                        await this.loadPrompts();
                        await this.loadStats();
                    } else {
                        this.showToast('同步失败: ' + result.error, 'error');
                    }
                } catch (error) {
                    this.showToast('同步失败: ' + error.message, 'error');
                }
            }
            
            async toggleFavorite(promptId) {
                try {
                    const prompt = await this.getPrompt(promptId);
                    if (!prompt) return;
                    
                    const response = await fetch(`/api/prompts/${promptId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            is_favorite: !prompt.is_favorite
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        this.showToast(prompt.is_favorite ? '已取消收藏' : '已添加收藏', 'success');
                        await this.loadPrompts();
                        await this.loadStats();
                    } else {
                        this.showToast('操作失败: ' + result.error, 'error');
                    }
                } catch (error) {
                    this.showToast('操作失败: ' + error.message, 'error');
                }
            }
            
            async deletePrompt(promptId) {
                if (!confirm('确定要删除这个提示词吗？')) {
                    return;
                }
                
                try {
                    const response = await fetch(`/api/prompts/${promptId}`, {
                        method: 'DELETE'
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        this.showToast('删除成功', 'success');
                        await this.loadPrompts();
                        await this.loadStats();
                    } else {
                        this.showToast('删除失败: ' + result.error, 'error');
                    }
                } catch (error) {
                    this.showToast('删除失败: ' + error.message, 'error');
                }
            }
            
            async exportData() {
                try {
                    const params = new URLSearchParams({
                        favorites_only: this.currentTab === 'favorite'
                    });
                    
                    const response = await fetch(`/api/export?${params}`);
                    
                    if (response.ok) {
                        const blob = await response.blob();
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `prompts_${this.currentTab}_${new Date().toISOString().split('T')[0]}.csv`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        
                        this.showToast('导出成功', 'success');
                    } else {
                        this.showToast('导出失败', 'error');
                    }
                } catch (error) {
                    this.showToast('导出失败: ' + error.message, 'error');
                }
            }
            
            async getPrompt(promptId) {
                try {
                    const response = await fetch(`/api/prompts/${promptId}`);
                    const result = await response.json();
                    return result.success ? result.data : null;
                } catch (error) {
                    return null;
                }
            }
            
            goToPage(page) {
                this.currentPage = page;
                this.loadPrompts();
            }
            
            showLoading(show) {
                document.getElementById('loading').style.display = show ? 'block' : 'none';
            }
            
            showToast(message, type = 'success') {
                const toast = document.createElement('div');
                toast.className = `toast ${type}`;
                toast.textContent = message;
                
                document.body.appendChild(toast);
                
                setTimeout(() => {
                    toast.classList.add('show');
                }, 10);
                
                setTimeout(() => {
                    toast.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(toast);
                    }, 300);
                }, 3000);
            }
            
            escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        }
        
        // 初始化应用
        let promptManager;
        document.addEventListener('DOMContentLoaded', () => {
            promptManager = new PromptManager();
        });
    </script>
</body>
</html>
